package top.xunfong.knowledge.service.impl;

import cn.hutool.core.util.ObjectUtil;
import top.xunfong.common.core.constant.redisKey.RedisKeyConstants;
import top.xunfong.common.core.exception.ServiceException;
import top.xunfong.domain.dto.OrderGrabbingDTO;
import top.xunfong.domain.dto.ResetFlashSaleDTO;
import top.xunfong.redis.annotation.RedisLockAnnotation;
import top.xunfong.redis.service.RedisService;
import top.xunfong.knowledge.service.FlashSaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FlashSaleServiceImpl implements FlashSaleService {

    @Autowired
    private RedisService redisService;


    @Override
    public void reset(ResetFlashSaleDTO dto) {
        for (String cid : dto.getData()) {
            // TODO 注意设置超时时间，具体的数据需以数据库为准，此处为demo
            redisService.setCacheObject(RedisKeyConstants.FLASH_SALE_KEY_INVENTORY + ":" + cid, dto.getNum());
        }
    }

    @Override
    @RedisLockAnnotation(key = "'" + RedisKeyConstants.FLASH_SALE_KEY_ORDER_GRABBING + "' + #dto.cid + ':' + #dto.user")
    public void orderGrabbing(OrderGrabbingDTO dto) {
        String rediskey = RedisKeyConstants.FLASH_SALE_KEY_INVENTORY + ":" + dto.getCid();
        // 校验是否还有库存
        Long num = redisService.getCacheObject(rediskey);
        if (ObjectUtil.isNotNull(num) && num > 0) {
            Long decr = redisService.decr(rediskey);
            if (ObjectUtil.isNotNull(decr) && decr >= 0) {
                // 减库存成功
                // 创建订单
                // 保存记录
            } else {
                // 超卖，恢复库存
                Long incr = redisService.incr(rediskey);
            }
        } else {
            throw new ServiceException("库存不足");
        }

    }
}
